package com.laowu.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.laowu.bean.ResponseMsg;
import com.laowu.constants.CodeConstants;

/**
 * 
 * @Title FilesConstoller.java
 * @Package com.laowu.controller
 * @Description 文件处理控制器，处理上传下载
 * @author LaoXu
 * @date 2018年9月12日
 * @version V1.0
 */
@Controller
@CrossOrigin
@RequestMapping("/files")
public class FilesConstoller {
	
	/**
	 * 单个文件上传
	 * @param multipartFile
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody ResponseMsg upload(@RequestParam("file") CommonsMultipartFile multipartFile, HttpServletRequest request) {
		try {
			// 获取保存文件的路径，位于项目目录下
			String path = request.getServletContext().getRealPath("/uploads");
			System.out.println(path);
			// 获取上传文件的文件名
			String fileName = multipartFile.getOriginalFilename();
			File file = new File(path + "/" + fileName);
			// 获取文件的输入流
			InputStream inputStream = multipartFile.getInputStream();
			// 将文件输入流拷贝至目标目录下
			FileUtils.copyInputStreamToFile(inputStream, file);
			// 关闭文件输入流
			if (null != inputStream) {
				inputStream.close();
			}
			return new ResponseMsg(CodeConstants.SUCCESSFUL, "文件上传成功！");
		} catch (IOException e) {
			e.printStackTrace();
			return new ResponseMsg(CodeConstants.ERROR, "文件上传失败!");
		}
	}
	
	@RequestMapping(value = "/getAllFiles", method = RequestMethod.GET)
	public @ResponseBody ResponseMsg getAllFiles(HttpServletRequest request) {
		// 获取保存文件的路径，位于项目目录下
		String path = request.getServletContext().getRealPath("/uploads");
		List<String> listFile = new ArrayList<String>();
		
		File file = new File(path);
		
		File[] files = file.listFiles();
		for (int i = 0, fLen = files.length; i < fLen; i++) {
			if (files[i].isFile()) {
				listFile.add(files[i].toString());
			}
		}
		return new ResponseMsg(CodeConstants.SUCCESSFUL, listFile);
	}
}
